package cn.vcjf.weapp.api.payment.service;

import cn.vcjf.weapp.api.goods.entity.GoodsOrder;
import cn.vcjf.weapp.api.goods.mapper.GoodsOrderMapper;
import cn.vcjf.weapp.api.payment.qfwxpay.service.AbstractQfWxPayAuth;
import cn.vcjf.weapp.api.payment.qfwxpay.model.VcQfPayReq;
import cn.vcjf.weapp.api.payment.qfwxpay.model.VcQfPayRes;
import cn.vcjf.weapp.api.payment.qfwxpay.service.QfApi.WechatPayService;
import cn.vcjf.weapp.api.payment.qfwxpay.service.QfApi.WechatPayServiceImpl;
import cn.vcjf.weapp.api.setting.entity.OrderOption;
import cn.vcjf.weapp.api.setting.mapper.OrderOptionMapper;
import cn.vcjf.weapp.common.exception.ServiceException;
import cn.vcjf.weapp.common.util.SysParamUtil;
import cn.vcjf.weapp.common.web.TableResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther: zhengzihang
 * @Date: 2018/10/16 16:29
 * @Description:
 */
@Service("abstractQfWxPayAuth")
public class QfWxPayServiceImpl extends AbstractQfWxPayAuth<GoodsOrder> {
	private Logger logger = LogManager.getLogger(QfWxPayServiceImpl.class);

	public static String merch_id = "merch_id";
	@Autowired
	private WechatPayService wechatPayService;
	@Resource
	private OrderOptionMapper orderOptionMapper;
	@Resource
	private GoodsOrderMapper goodsOrderMapper;

	private static Map<Integer, String> merchid_cache = new ConcurrentHashMap<>();
	/**
	 *  根据数据库配置查询商户的钱方子商户id
	 */
	@Override
	public String getMerchId() {
		OrderOption query = new OrderOption();
		if (merchid_cache.get(query.getSysUserId()) != null) {
			return merchid_cache.get(query.getSysUserId());
		} else {
			query.setKey(merch_id);
			OrderOption option = orderOptionMapper.selectOne(query);
			if (option != null && StringUtils.isNotBlank(option.getValue())) {
				merchid_cache.put(option.getSysUserId(), option.getValue());
				return option.getValue();
			}
			throw ServiceException.Exception("商户未配置收款账号");
		}
//		return MERCH_ID;
	}

	@Override
	protected void doCheckRequestParams(HttpServletRequest request) {
		String orderNo = request.getParameter("orderNo");
		String goodsName = request.getParameter("goodsName");
		String money = request.getParameter("money");
		String merchName = request.getParameter("merchName");
		if (StringUtils.isAnyBlank(orderNo, goodsName, money,merchName)) {
			throw new IllegalArgumentException("请检查下单参数!");
		}
		GoodsOrder query = new GoodsOrder();
		query.setOrderNo(orderNo);
		GoodsOrder goodsOrder = goodsOrderMapper.selectOne(query);
		if (goodsOrder == null ||goodsOrder.getStatus()!=GoodsOrder.ORDER_STATUS_CREATING) {
			throw new IllegalArgumentException("请检查订单状态!");
		}
	}

	@Override
	protected String getUnifiedOrderUrl() {
		return null;
	}

	@Override
	public void doUnifiedOrder(HttpServletResponse response, String openId, String queryString) throws IOException {
		VcQfPayReq vcQfPayReq = new VcQfPayReq();
		Map<String, String> map = new HashMap<>();
		logger.info("支付下单开始>>>>>>>>>>>>>queryString:{}",queryString);
		String[] strings = queryString.split("&");
		for(String param : strings){
			String[] split = param.split("=");
			map.put(split[0],split[1]);
		}
		logger.info("支付下单开始>>>>>>>>>>>>>Map:{}",map);

		vcQfPayReq.setOutTradeNo( map.get("orderNo"));
		vcQfPayReq.setGoodsName(map.get("goodsName"));
		vcQfPayReq.setTxamt(map.get("money"));
		vcQfPayReq.setMerchName(map.get("merchName"));
		if(StringUtils.isNotBlank(map.get("minapp"))){
			vcQfPayReq.setPayType("800213");
		}
		vcQfPayReq.setMchid(getMerchId());

		vcQfPayReq.setSubOpenid(openId);

		VcQfPayRes vcQfPayRes = wechatPayService.doPay(vcQfPayReq);
		logger.info("支付下单结果>>>>>>>>>>>>>VcQfPayRes:{}", JSON.toJSONString(vcQfPayRes));
		GoodsOrder goodsOrder = new GoodsOrder();
		goodsOrder.setOrderNo(vcQfPayReq.getOutTradeNo());

		//下单成功,跳转支付jsp页面
		if (vcQfPayRes.isOK()) {
			goodsOrder.setStatus(GoodsOrder.ORDER_STATUS_WAITPAY);
			goodsOrder.setOrderDes("下单成功");
			goodsOrder.setpResult(vcQfPayRes.getResult());
			goodsOrderMapper.updateGoodsOrderByOrderNo(goodsOrder);

			String resParam = vcQfPayRes.getResParam();
//				String resStr = resParam.replace("}", "").replace("{", "").replace("\"", "").replace(":", "=").replace(",", "&").replace(" ", "");

			JSONObject jsonObject = JSON.parseObject(resParam);
			//小程序支付
			if(StringUtils.isNotBlank(map.get("minapp"))){
				response.getWriter().print(TableResult.DateResult(resParam));
				//公众号支付
			}else {
				response.sendRedirect(WechatPayServiceImpl.getPayUrl(vcQfPayReq,jsonObject));
			}
//				response.sendRedirect(BASE_URL + "/pages/wxpay.jsp?" + resStr);
		} else if(!vcQfPayRes.isWait()){
			goodsOrder.setStatus(GoodsOrder.ORDER_STATUS_UNORDER_FAILED);
			goodsOrder.setOrderDes("下单失败:"+vcQfPayRes.getErrMsg());
			goodsOrder.setpResult(vcQfPayRes.getResult());
			goodsOrderMapper.updateGoodsOrderByOrderNo(goodsOrder);

			response.getWriter().print(vcQfPayRes.getErrMsg());
		}else {
			goodsOrder.setStatus(GoodsOrder.ORDER_STATUS_CREATING);
			goodsOrder.setOrderDes("下单中");
			goodsOrder.setpResult(vcQfPayRes.getResult());
			goodsOrderMapper.updateGoodsOrderByOrderNo(goodsOrder);

			response.getWriter().print(vcQfPayRes.getErrMsg());
		}
	}

	@Override
	protected String getThisServletUrl() {

		return SysParamUtil.getParam("wxpay.doUnifiedOrderUrl");
	}

}
